<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Spring Cloud天气项目微服务,">










<meta name="description" content="本文学习《从天气项目看Spring Cloud微服务治理》第十章，主要内容为：微服务的熔断机制视频课程地址：https://coding.imooc.com/class/chapter/177.html项目代码地址： https://gitee.com/aiolos123/spring-cloud-weather">
<meta name="keywords" content="Spring Cloud天气项目微服务">
<meta property="og:type" content="article">
<meta property="og:title" content="【八】从天气项目看Spring Cloud微服务治理——微服务的熔断机制">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/12/06/spring-cloud-weather-8/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文学习《从天气项目看Spring Cloud微服务治理》第十章，主要内容为：微服务的熔断机制视频课程地址：https://coding.imooc.com/class/chapter/177.html项目代码地址： https://gitee.com/aiolos123/spring-cloud-weather">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191206145059036.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191206145542591.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191206170522093.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191206171311114.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191206171414465.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191209173552281.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191209175121440.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191210153910540.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191210154121884.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191210154350163.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191210155101545.jpg">
<meta property="og:updated_time" content="2019-12-10T07:51:43.104Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【八】从天气项目看Spring Cloud微服务治理——微服务的熔断机制">
<meta name="twitter:description" content="本文学习《从天气项目看Spring Cloud微服务治理》第十章，主要内容为：微服务的熔断机制视频课程地址：https://coding.imooc.com/class/chapter/177.html项目代码地址： https://gitee.com/aiolos123/spring-cloud-weather">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20191206145059036.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/12/06/spring-cloud-weather-8/">





  <title>【八】从天气项目看Spring Cloud微服务治理——微服务的熔断机制 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/12/06/spring-cloud-weather-8/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【八】从天气项目看Spring Cloud微服务治理——微服务的熔断机制</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-12-06T05:59:13+08:00">
                2019-12-06
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Spring-Cloud/" itemprop="url" rel="index">
                    <span itemprop="name">Spring Cloud</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文学习《从天气项目看Spring Cloud微服务治理》第十章，主要内容为：微服务的熔断机制<br>视频课程地址：<a href="https://coding.imooc.com/class/chapter/177.html" target="_blank" rel="noopener">https://coding.imooc.com/class/chapter/177.html</a><br>项目代码地址： <a href="https://gitee.com/aiolos123/spring-cloud-weather" target="_blank" rel="noopener">https://gitee.com/aiolos123/spring-cloud-weather</a></p>
<a id="more"></a>

<h2 id="什么是服务的熔断"><a href="#什么是服务的熔断" class="headerlink" title="什么是服务的熔断"></a>什么是服务的熔断</h2><ol>
<li>什么是服务的熔断<blockquote>
<p>当服务过载、流量激增时，对该服务的调用执行了熔断、对于后续请求，不再继续调用该目标服务，而是直接返回默认响应，从而可以快速释放资源，进而保护系统避免出现”雪崩”</p>
</blockquote>
</li>
</ol>
<p>雪崩：一个服务不可用、导致所有依赖它的服务也都不可用，最终导致系统不可用，这就是雪崩效应；</p>
<ol start="2">
<li>实现服务熔断的方式(服务熔断的原理)——断路器<blockquote>
<p>断路器(类似于电路的保险丝): 将受保护的服务封装在一个可以监控故障的断路器对象中，当故障达到一定阈值时，断路器就断开，后续调用不再发往受保存的服务中，而是由断路器对象直接返回错误信息。</p>
</blockquote>
</li>
</ol>
<p>断路器模式： 致力于防止应用程序反复尝试执行可能失败的操作，避免应用程序在故障被修复期间的资源浪费；同时监控故障是否修复，待故障修复后应用程序又可访问服务。</p>
<p>Microsoft Azure断路器模式示意图：<br><img src="/blog/images/20191206145059036.jpg" alt="Microsoft实现断路器模式示意图"><br>Hystrix断路器模式示意图：<br><img src="/blog/images/20191206145542591.jpg" alt="Hystrix实现断路器模式示意图"></p>
<ol start="3">
<li><p>服务熔断的意义</p>
<blockquote>
<p>a. 保护系统处于稳定状态<br>b. 减少性能损耗<br>c. 及时响应<br>d. 阀值可定制</p>
</blockquote>
</li>
<li><p>服务熔断的功能</p>
<blockquote>
<p>a. 处理特定异常<br>b. 日志记录<br>c. 测试失败的操作<br>d. 手动复位(手动关闭熔断器)<br>e. 支持高并发<br>f. 加速断路<br>g. 重试失败请求</p>
</blockquote>
</li>
<li><p>服务熔断与服务降级的区别<br>相同点：目的一致(从可用性、可靠性方面解决系统的崩溃、保护系统)；表现形式类似；粒度一致(从服务级别)；<br>不同点：触发条件不同(熔断:某个下游服务故障引起； 降级:系统整体负荷引起)<br>管理目标的层次不同(熔断:针对整个框架级的每个服务; 降级:针对业务层次，一般先从外围业务开始)</p>
</li>
</ol>
<h2 id="如何集成Hystrix-hystrix-demo"><a href="#如何集成Hystrix-hystrix-demo" class="headerlink" title="如何集成Hystrix(hystrix-demo)"></a>如何集成Hystrix(hystrix-demo)</h2><ol>
<li><p>创建module、引入依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--eureka client--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-netflix-eureka-client<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--feign--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-openfeign<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>2.0.0.M6<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br><span class="line"><span class="comment">&lt;!--hystrix--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-netflix-hystrix<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>启动类中添加@EnableDiscoveryClient、@EnableFeignClients和@EnableCircuitBreaker注解</p>
</li>
<li><p>在通过Feign调用其他微服务的Controller方法上添加@HystrixCommand注解</p>
<blockquote>
<p>当通过Feign调用的其他服务无法响应时，@HystrixCommand注解将返回fallbackMethod指定的方法的返回值</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191206170522093.jpg" alt="添加@HystrixCommand注解"></p>
<ol start="4">
<li><p>修改配置文件(同配置Feign)</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">spring<span class="selector-class">.application</span><span class="selector-class">.name</span>=hystrix-demo</span><br><span class="line">eureka<span class="selector-class">.client</span><span class="selector-class">.serviceUrl</span><span class="selector-class">.defaultZone</span>=http:<span class="comment">//localhost:8761/eureka/</span></span><br><span class="line">feign<span class="selector-class">.client</span><span class="selector-class">.config</span><span class="selector-class">.feignName</span><span class="selector-class">.connect-timeout</span>=<span class="number">5000</span></span><br><span class="line">feign<span class="selector-class">.client</span><span class="selector-class">.config</span><span class="selector-class">.feignName</span><span class="selector-class">.read-timeout</span>=<span class="number">5000</span></span><br><span class="line">server.port=<span class="number">8087</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>先后启动Eureka Server、City-data-Service，hystrix-demo三个服务，并访问hystrix-demo的接口<a href="http://localhost:8087/cities，测试各微服务是否可以正常运行" target="_blank" rel="noopener">http://localhost:8087/cities，测试各微服务是否可以正常运行</a><br><img src="/blog/images/20191206171311114.jpg" alt="测试各微服务是否可以正常运行"></p>
</li>
</ol>
<p>然后停止City-data-Service服务，查看熔断器是否可以正常工作<br><img src="/blog/images/20191206171414465.jpg" alt="查看熔断器是否可以正常工作"></p>
<h2 id="实现天气微服务系统中的熔断机制"><a href="#实现天气微服务系统中的熔断机制" class="headerlink" title="实现天气微服务系统中的熔断机制"></a>实现天气微服务系统中的熔断机制</h2><ol>
<li><p>需要修改的微服务：weather-report-service<br><img src="/blog/images/20191209173552281.jpg" alt="实现天气微服务系统中的熔断机制"></p>
</li>
<li><p>在weather-report-service中再引入hystrix依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--hystrix--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.cloud<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-cloud-starter-netflix-hystrix<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>启动类中再添加@EnableCircuitBreaker断路器注解</p>
</li>
<li><p>修改配置文件，便于直接在@FeignClient注解上指定fallback类即可，因为FeignClient内置了Hystrix回调函数的支持</p>
<blockquote>
<p>而无需通过Feign调用其他微服务的Controller方法上添加@HystrixCommand注解</p>
</blockquote>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 启动feign对hystrix的支持</span></span><br><span class="line"><span class="attr">feign.hystrix.enabled</span> = <span class="literal">true</span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p><img src="/blog/images/20191209175121440.jpg" alt="直接在@FeignClient注解上指定fallback类即可"></p>
<ol start="6">
<li><p>编写fallback类</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 服务请求失败时默认返回的数据</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">@Component</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DataClientFallback</span> <span class="keyword">implements</span> <span class="title">DataClient</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 城市列表微服务请求失败时默认返回的数据: 深圳和惠州两个城市</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    @Override</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">List</span>&lt;City&gt; getCityList() throws <span class="keyword">Exception</span> &#123;</span><br><span class="line">        <span class="keyword">List</span>&lt;City&gt; <span class="keyword">list</span> = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        City szcity = <span class="keyword">new</span> City();</span><br><span class="line">        szcity.setCityId(<span class="string">"101280601"</span>);</span><br><span class="line">        szcity.setCityName(<span class="string">"深圳"</span>);</span><br><span class="line">        <span class="keyword">list</span>.add(szcity);</span><br><span class="line"></span><br><span class="line">        City hzcity = <span class="keyword">new</span> City();</span><br><span class="line">        hzcity.setCityId(<span class="string">"101280301"</span>);</span><br><span class="line">        hzcity.setCityName(<span class="string">"惠州"</span>);</span><br><span class="line">        <span class="keyword">list</span>.add(hzcity);</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">list</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 天气数据微服务失败时，直接返回null即可</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> cityId</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    @Override</span><br><span class="line">    <span class="keyword">public</span> WeatherResponse getDataByCityId(String cityId) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>修改前端页面，增加null判断</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;<span class="selector-tag">div</span> <span class="selector-tag">th</span>:<span class="keyword">if</span>=<span class="string">"$&#123;reportModel.report&#125; != null"</span>&gt;天气数据API服务暂不可用！&lt;/div&gt;</span><br><span class="line">&lt;<span class="selector-tag">div</span> <span class="selector-tag">th</span>:<span class="keyword">if</span>=<span class="string">"$&#123;reportModel.report&#125; == null"</span>&gt;</span><br><span class="line">    &lt;<span class="selector-tag">div</span> class=<span class="string">"row"</span>&gt;</span><br><span class="line">        &lt;p&gt;</span><br><span class="line">            天气数据API服务暂不可用！</span><br><span class="line">        &lt;/p&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">&lt;/div&gt;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h2 id="测试微服务熔断机制"><a href="#测试微服务熔断机制" class="headerlink" title="测试微服务熔断机制"></a>测试微服务熔断机制</h2><ol>
<li><p>依次启动Redis、Eureka Server(eureka-server-integration-demo)、weather-city-service、weather-collection-service、weather-config-server、weather-data-service、weather-report-service、weather-zuul-gateway等7个微服务</p>
</li>
<li><p>访问Eureka Server管理界面 <a href="http://localhost:8761/" target="_blank" rel="noopener">http://localhost:8761/</a> ，查看7个微服务是否正常启动<br><img src="/blog/images/20191210153910540.jpg" alt="查看7个微服务是否正常启动"></p>
</li>
<li><p>访问天气预报微服务(weather-report-service)接口 <a href="http://localhost:8084/report/cityId/101280102，验证各微服务可以正常使用" target="_blank" rel="noopener">http://localhost:8084/report/cityId/101280102，验证各微服务可以正常使用</a><br><img src="/blog/images/20191210154121884.jpg" alt="验证各微服务可以正常使用"></p>
</li>
<li><p>关闭weather-city-service微服务模拟访问服务失败，测试熔断机制工作正常：</p>
<blockquote>
<p>由上一节的第6小节代码可知：关闭weather-city-service微服务后，默认只返回2个城市列表</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191210154350163.jpg" alt="测试熔断机制工作正常"></p>
<ol start="5">
<li>关闭weather-data-service微服务模拟访问服务失败，测试熔断机制工作正常：<blockquote>
<p>由上一节的第6小节代码可知：关闭weather-data-service微服务后，默认返回null并显示’天气数据API服务暂不可用！’</p>
</blockquote>
</li>
</ol>
<p><img src="/blog/images/20191210155101545.jpg" alt="测试熔断机制工作正常"></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Spring-Cloud天气项目微服务/" rel="tag"># Spring Cloud天气项目微服务</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/12/04/spring-cloud-weather-7/" rel="next" title="【七】从天气项目看Spring Cloud微服务治理——微服务的集中化配置">
                <i class="fa fa-chevron-left"></i> 【七】从天气项目看Spring Cloud微服务治理——微服务的集中化配置
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/12/08/java-interview-offer-1/" rel="prev" title="【一】剑指Java面试Offer直通车-课程简介与Java底层知识：JVM">
                【一】剑指Java面试Offer直通车-课程简介与Java底层知识：JVM <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#什么是服务的熔断"><span class="nav-number">1.</span> <span class="nav-text">什么是服务的熔断</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#如何集成Hystrix-hystrix-demo"><span class="nav-number">2.</span> <span class="nav-text">如何集成Hystrix(hystrix-demo)</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现天气微服务系统中的熔断机制"><span class="nav-number">3.</span> <span class="nav-text">实现天气微服务系统中的熔断机制</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#测试微服务熔断机制"><span class="nav-number">4.</span> <span class="nav-text">测试微服务熔断机制</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
